package fr.web325.servlet.client.register;

import fr.web325.bean.User;
import fr.web325.dao.UserDao;
import fr.web325.utils.CodeUtils;
import fr.web325.utils.EmailUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/shop/client/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        try {
             BeanUtils.populate( user,req.getParameterMap());
             System.out.println(user.toString());
             String username = req.getParameter("username");
             user.setRole("普通用户");
             user.setRegistTime(new Date());
             user.setIntroduce("");
             String code = new CodeUtils().getActiveCode(username);
             user.setActiveCode(code);
             String msg = new UserDao().addUser(user);
             if(msg.equals("注册成功")){
                 String ActiveUrl = req.getContextPath()+"/shop/client/activation?ActivationCode="+code;
                 // 发送邮件
                 new EmailUtils().sendEmail("大白传智书城","您已经注册成功,请点击该链接尽快激活登录您的账号!  "+ActiveUrl);
                 // 请求登录
                 req.setAttribute("msg","请到邮箱中激活后在进行登录");
                 req.getRequestDispatcher("/shop/client/tips.jsp").forward(req,resp);
             }else{
                 req.setAttribute("msg",msg);
                 req.getRequestDispatcher("/shop/error/register.jsp").forward(req,resp);
             }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
